package com.ln.lnzw.activity;

import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.blankj.utilcode.util.ActivityUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.listener.OnItemClickListener;
import com.ln.lnzw.R;
import com.ln.lnzw.adapter.ServerSubscribeTopAdapter;
import com.ln.lnzw.app.AppConstant;
import com.ln.lnzw.base.BaseActivity;

import com.ln.lnzw.bean.ServerSubscribeRecomBean;
import com.ln.lnzw.bean.ServerSubscribeRecomNetBean;
import com.ln.lnzw.bean.UniversalBean;
import com.ln.lnzw.event.SubscribeChangeEvent;
import com.ln.lnzw.net.HttpMethods;

import org.greenrobot.eventbus.EventBus;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.Unbinder;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;

/**
 * 作者 : wlt
 * 创建时间:  2018-04-26
 * QQ : 1346947404
 * 邮箱:wanglt_android@163.com
 * 类说明:
 * In me the tiger sniffs the rose
 */

public class ServiceCatagoryListDetailsActivity extends BaseActivity {

    private static final String TAG = "ServiceCatagoryListDeta";

    Unbinder unbinder;

    @BindView(R.id.iv_back)
    ImageView iv_back;

    @BindView(R.id.tv_title_bar)
    TextView tv_title_bar;

    @BindView(R.id.rv_list)
    RecyclerView rv_list;
    /**
     * 用户id
     */
    private String userId;
    /**
     * 服务名称
     */
    private String appName;
    /**
     * 分类id
     */
    private String serverKey;
    /**
     * 数据集合
     */
    private List<ServerSubscribeRecomBean> list = new ArrayList<>();
    /**
     * 列表数据适配器
     */
    private ServerSubscribeTopAdapter mAdapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_fuwu_list);
        unbinder = ButterKnife.bind(this);
        appName = getIntent().getStringExtra("name");
        serverKey = getIntent().getStringExtra("serverKey");
        initView();
        initData();

    }

    /**
     * 初始化控件,设置layoutmanager,设置名称,设置点击事件等
     */
    private void initView() {
        tv_title_bar.setText(appName);
        iv_back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });

        rv_list.setLayoutManager(new LinearLayoutManager(this));
        mAdapter = new ServerSubscribeTopAdapter(R.layout.item_service_recom_top,list);
        rv_list.setAdapter(mAdapter);

        rv_list.addOnItemTouchListener(new OnItemClickListener() {
            @Override
            public void onSimpleItemClick(BaseQuickAdapter adapter, View view, int position) {
                Bundle bundle = new Bundle();
                bundle.putString("name",list.get(position).getAppName());
                bundle.putString("url",list.get(position).getAppMobileUrl());
                ActivityUtils.startActivity(bundle, ServiceAppDetailActivity.class);
            }
        });

        mAdapter.setOnItemChildClickListener(new BaseQuickAdapter.OnItemChildClickListener() {
            @Override
            public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {
                if (view.getId() == R.id.iv_recom_subscribe){
                    if (getIsLogin()){
                        if (list.get(position).getRecommend().equals("1")){//当前为已订阅,执行取消订阅方法
                            cancleSub(list.get(position).getAppUuid());
                        }else {//当前为未订阅,执行订阅方法
                            addSub(list.get(position).getAppUuid());
                        }
                    }else {
                        toLogin();
                    }

                }
            }
        });
    }

    /**
     * 网络获取数据
     */
    private void initData() {
        userId = activity.spUtils.getString(AppConstant.USER_UID);

        HttpMethods.getInstanceCenter().info.getServiceCateSers(userId,serverKey)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<ServerSubscribeRecomNetBean>() {
                    @Override
                    public void onSubscribe(Disposable d) {
                        addDisposable(d);
                    }

                    @Override
                    public void onNext(ServerSubscribeRecomNetBean serverSubscribeRecomNetBean) {
                        if (!list.isEmpty()){list.clear();}
                        if (null != serverSubscribeRecomNetBean.getResult())
                        list.addAll(serverSubscribeRecomNetBean.getResult());
                    }

                    @Override
                    public void onError(Throwable e) {
                        Log.e(TAG, "onError:获取顶部失败 "+e.toString() );
                    }

                    @Override
                    public void onComplete() {
                        mAdapter.setNewData(list);
                        mAdapter.notifyDataSetChanged();
                    }
                });
    }

    /**
     * 添加订阅
     * @param appUuid 服务项目的唯一标识
     */
    private void addSub(String appUuid){
        userId = activity.spUtils.getString(AppConstant.USER_UID);

        HttpMethods.getInstanceCenter().info.addSub(userId,appUuid)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<UniversalBean>() {
                    @Override
                    public void onSubscribe(Disposable d) {
                        addDisposable(d);
                    }

                    @Override
                    public void onNext(UniversalBean universalBean) {
                        Log.e(TAG, "onNext: 添加订阅"+universalBean.toString() );
                        if (universalBean.getMsg().equals("订阅成功")){
                            ToastUtils.showShort("订阅成功");
                            initData();
                        }
                    }

                    @Override
                    public void onError(Throwable e) {
                        Log.e(TAG, "onError:订阅失败 "+e.toString() );
                        ToastUtils.showShort("网络故障,订阅失败");
                    }

                    @Override
                    public void onComplete() {
                        EventBus.getDefault().post(new SubscribeChangeEvent("二级页面"));
                    }
                });

    }

    /**
     * 取消订阅
     * @param appUuid 服务栏目的唯一标识
     */
    private void cancleSub(String appUuid){
        userId = activity.spUtils.getString(AppConstant.USER_UID);

        HttpMethods.getInstanceCenter().info.cancleSub(userId,appUuid)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<UniversalBean>() {
                    @Override
                    public void onSubscribe(Disposable d) {
                        addDisposable(d);
                    }

                    @Override
                    public void onNext(UniversalBean universalBean) {
                        Log.e(TAG, "onNext: 取消订阅"+universalBean.toString() );
                        if (universalBean.getMsg().equals("取消成功")){
                            ToastUtils.showShort("取消订阅成功");
                            initData();
                        }
                    }

                    @Override
                    public void onError(Throwable e) {
                        Log.e(TAG, "onError:取消订阅失败 "+e.toString() );
                        ToastUtils.showShort("网络故障,取消订阅失败");
                    }

                    @Override
                    public void onComplete() {
                        EventBus.getDefault().post(new SubscribeChangeEvent("二级页面"));
                    }
                });
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        unbinder.unbind();
        dispose();
    }
    /**
     * 判断是否已经登录,用token做依据
     * @return 用户是否已经登录
     */
    private boolean getIsLogin(){
        return !activity.spUtils.getString(AppConstant.TOKEN).isEmpty();
    }

    /**
     * 跳转登录页面,当用户未登录的时候跳转到登录页的方法
     */
    private void toLogin(){
        ActivityUtils.startActivity(activity, LoginActivity.class);
    }
}
